package com.studyday.sjx01;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;


@Controller
public class SJX01App {
	@RequestMapping("sc")
	public String uploadpage() {
		return "Html5";
	}

	/**
	 * 文件上传
	 */
	@RequestMapping(value = "/uploadFiles")
	public void upload2(HttpServletRequest servletRequest, MultipartFile[] multipartFile) {

		for (MultipartFile multipartFile1 : multipartFile) {
			String fileName = multipartFile1.getOriginalFilename();
			try {
				File f = createDownloadPath();
				File file = new File(f.getAbsolutePath(), fileName);
				multipartFile1.transferTo(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 文件列表
	 */
	@RequestMapping("xz")
	public String fileListPage(HttpServletRequest request) {
		List<String> paths = new ArrayList<String>();
		//System.out.println(MyParam.downloadFilePath);
		paths = getAllFilePaths(new File(MyParam.downloadFilePath), paths);
		request.setAttribute("fileList", paths);
		return "fileListPage";
	}

	private static List<String> getAllFilePaths(File filePath, List<String> filePaths) {
		File[] files = filePath.listFiles();
		if (files == null) {
			return filePaths;
		}
		for (File f : files) {
			if (f.isDirectory()) {
				//filePaths.add(f.getPath());
				getAllFilePaths(f, filePaths);
			} else {
				filePaths.add(f.getPath());
			}
		}
		return filePaths;
	}

 
	@RequestMapping("download")
	public void downLoad(String file, HttpServletResponse response, boolean isOnLine)  {
		System.out.println(file);
		String filePath = URLDecoder.decode(file);
		System.out.println(filePath);
		System.out.println(isOnLine);
		File f = null;
		OutputStream out =  null;
		BufferedInputStream br = null;
		URL u = null;
		try {
			f = new File(filePath);
		if (!f.exists()) {
			response.sendError(404, "File not found!");
			return;
		}
		br = new BufferedInputStream(new FileInputStream(f));
		byte[] buf = new byte[2048];
		int len = 0;

		response.reset();
		if (isOnLine) { // 在线打开方式
			u = new URL("file:///" + filePath);
			response.setContentType(u.openConnection().getContentType());
			response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(f.getName()));
			//文件大小已知，设置文件大小
			response.setContentLength((int) f.length());
			// 文件名应该编码成UTF-8
		} else { // 纯下载方式
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName()));
			response.setContentLength((int) f.length());
		}
		out = response.getOutputStream();
		while ((len = br.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		} catch(Exception e) {
			e.printStackTrace();
		}finally {
	
			try {
				if(br!=null) {
				br.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(out!=null) {
				out.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			
		 
			 
		}

	}

	
	
	

	//	/**
//	 * 下载文件
//	 * @throws UnsupportedEncodingException 
//	 */
//	@RequestMapping("download")
//	public void download(String file,HttpServletResponse response) throws UnsupportedEncodingException {
//		// 在servlet里读取资源
//		// 得到资源的绝对地址
//		//String path = this.getServletContext().getRealPath("/download/1.jpg");
//		// 截取文件地址，最后一个斜杠后面的文件名
//		//String filename = path.substring(path.lastIndexOf("\\") + 1);
//			
//		// 设置以何种方式打开文件
//		// 下载的图片名为中文的，修改编码
//		file = URLDecoder.decode(file);
//		File f = new File(file);
//		System.out.println(f.getName());
//		response.setHeader("Content-Disposition", "attachment;filename =" + URLEncoder.encode(f.getName(), "utf-8"));
//		//response.setHeader("Content-Disposition", "attachment;filename" + f.getName());
//		InputStream in = null;
//		OutputStream out = null;
//
//		try {
//			in = new FileInputStream(f);
//			int len = 0;
//			byte buffer[] = new byte[1024];
//			out = response.getOutputStream();
//			while ((len = in.read(buffer)) > 0) {
//				out.write(buffer, 0, len);
//			}
//		} catch(FileNotFoundException fileNotFoundException) {
//			fileNotFoundException.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		finally {
//			if (in != null) {
//				try {
//					in.close();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}

	/**
	 * 创建文件夹目录
	 * 
	 * @return
	 */
	private File createDownloadPath() {
		File f = new File(MyParam.uploadFilePath);
		// 最简单法则
		if (!f.exists()) {
			f.mkdir();
		}
		return f;
	}

}